package com.huatai.exchange.deal;

import com.faneui.common.exception.BusinessException;
import com.faneui.integration.smb.SmbFileUtils;
import com.huatai.exchange.dal.model.ExcDataFileInfo;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.facade.FileSourceConstants;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;
import java.util.UUID;

@Service("fileCreateSmbDealService")
public class FileCreateSmbDealServiceImpl extends AbstractFileCreateDealServiceImpl implements FileCreateDealService{

    void generate( Map<String, Object> valueMap, ExcDataFileInfo dataFileInfo,StringBuffer fileNames, StringBuffer filePaths) throws BusinessException {
        String tmpFilePath = tmpFile + UUID.randomUUID().toString();
        File f = new File(tmpFilePath);
        try{
            String baseSmbFileUrl = (String) valueMap.get(FileSourceConstants.SMB_URL)  ;
            String smbFileUrl =  formatStr(baseSmbFileUrl, valueMap);
            NtlmPasswordAuthentication auth = getAuth(valueMap ) ;
            String fileName = formatStr(dataFileInfo.getFileName(), valueMap);

            SmbFile smbFile = new SmbFile(smbFileUrl, auth);
            if (!smbFile.exists()) {
                throw new BusinessException("路径：[" + smbFileUrl + "]数据无不全 ");
            } else {
                SmbFileUtils.copyLocalFileFromRemote(f, smbFileUrl, auth);
                String filePath = fileOperateService.uploadFile(f);
                filePaths.append(",").append(filePath);
                fileNames.append(",").append(fileName);
                valueMap.put(Contents.FILE_GC, valueMap.get(Contents.FILE_GC) + "," + filePath);
            }
        }catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }finally {
            f.deleteOnExit();
        }
    }
}
